from typing import List
from app.models.conversation import Conversation, DialogueType
from app.models.message import Message
from app.core.database import get_db, AsyncSessionLocal
from sqlalchemy import desc, select, delete
from typing import List


class ConversationService:
    @staticmethod
    async def create_conversation(user_id: int) -> int:
        async with AsyncSessionLocal() as session:
            try:
                conversation = Conversation(
                    user_id=user_id, 
                    title="新对话",
                    dialogue_type=DialogueType.NORMAL  # 使用字符串值
                )
                session.add(conversation)
                await session.commit()
                await session.refresh(conversation)
                return conversation.id
            except Exception as e:
                await session.rollback()
                raise e
    
    @staticmethod
    async def get_user_conversations(user_id: int) -> List[Conversation]:
        async with AsyncSessionLocal() as session:
            result = await session.execute(
                select(Conversation).filter(
                    Conversation.user_id == user_id
                ).order_by(desc(Conversation.updated_at))
            )
            conversations = result.scalars().all()
            # 确保返回的会话对象包含所有必要的字段
            return [{
                'id': conv.id,
                'user_id': conv.user_id,
                'title': conv.title,
                'created_at': conv.created_at,
                'updated_at': conv.updated_at,
                'status': conv.status,
                'dialogue_type': conv.dialogue_type
            } for conv in conversations]
    
    @staticmethod
    async def get_conversation_messages(conversation_id: int, 
                                        user_id: int) -> List[Message]:
        async with AsyncSessionLocal() as session:
            result = await session.execute(
                select(Conversation).filter(
                    Conversation.id == conversation_id,
                    Conversation.user_id == user_id
                )
            )
            conversation = result.scalars().first()
            
            if not conversation:
                return []
                
            result = await session.execute(
                select(Message).filter(
                    Message.conversation_id == conversation_id
                ).order_by(Message.created_at)
            )
            messages = result.scalars().all()
            # 确保返回的消息对象包含所有必要的字段
            return [{
                'id': msg.id,
                'conversation_id': msg.conversation_id,
                'role': 'user' if msg.sender == 'user' else 'assistant',  # 将sender转换为role
                'content': msg.content,
                'created_at': msg.created_at,
                'message_type': msg.message_type
            } for msg in messages]
    
    @staticmethod
    async def delete_conversation(conversation_id: int, user_id: int) -> bool:
        async with AsyncSessionLocal() as session:
            try:
                result = await session.execute(
                    select(Conversation).filter(
                        Conversation.id == conversation_id,
                        Conversation.user_id == user_id
                    )
                )
                conversation = result.scalars().first()
                
                if conversation:
                    await session.delete(conversation)
                    await session.commit()
                    return True
                return False
            except Exception as e:
                await session.rollback()
                raise e
            
    @staticmethod
    async def update_conversation_title(conversation_id: int, 
                                        user_id: int, 
                                        title: str) -> bool:
        async with AsyncSessionLocal() as session:
            try:
                result = await session.execute(
                    select(Conversation).filter(
                        Conversation.id == conversation_id,
                        Conversation.user_id == user_id
                    )
                )
                conversation = result.scalars().first()
                
                if conversation:
                    conversation.title = title
                    await session.commit()
                    await session.refresh(conversation)  # 刷新对象以确保更新生效
                    return True
                return False
            except Exception as e:
                await session.rollback()
                raise e

    @staticmethod
    async def get_conversation(conversation_id: int, 
                               user_id: int) -> Conversation:
        async with AsyncSessionLocal() as session:
            result = await session.execute(
                select(Conversation).filter(
                    Conversation.id == conversation_id,
                    Conversation.user_id == user_id
                )
            )
            return result.scalars().first()
            
    @staticmethod
    async def clear_conversation_messages(conversation_id: int, 
                                          user_id: int) -> bool:
        """
        清空会话中的所有消息但保留会话本身
        
        Args:
            conversation_id (int): 会话ID
            user_id (int): 用户ID
            
        Returns:
            bool: 操作是否成功
        """
        # 首先验证会话是否存在且属于该用户
        conversation = await ConversationService.get_conversation(conversation_id, user_id)
        if not conversation:
            return False
            
        # 删除会话中的所有消息
        async with AsyncSessionLocal() as session:
            try:
                await session.execute(
                    delete(Message).where(Message.conversation_id == conversation_id)
                )
                await session.commit()
                return True
            except Exception as e:
                await session.rollback()
                raise e
            
    @staticmethod
    async def save_message(conversation_id: int, 
                           content: str, 
                           role: str) -> Message:
        """
        保存消息到数据库
        
        Args:
            conversation_id (int): 会话ID
            content (str): 消息内容
            role (str): 发送者角色 ('user' 或 'assistant')
            
        Returns:
            Message: 保存的消息对象
            
        Raises:
            Exception: 数据库操作异常
        """
        async with AsyncSessionLocal() as session:
            try:
                message = Message(
                    conversation_id=conversation_id,
                    content=content,
                    sender=role
                )
                session.add(message)
                await session.commit()
                await session.refresh(message)
                return message
            except Exception as e:
                await session.rollback()
                raise e